using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace SharpSoft.Net.Protocols
{
    using Newtonsoft.Json;
    using System.Threading.Tasks;

    public class NetMessageStreamReader : BinaryReader
    {
        public NetMessageStreamReader(Stream stream) : base(stream)
        {
        }

        public override int Read()
        {
            return base.Read();
        }
        [System.Diagnostics.DebuggerStepThrough]
        public override byte ReadByte()
        {
            return base.ReadByte();
        }
        public override int Read(byte[] buffer, int index, int count)
        {
            try
            {
                return base.Read(buffer, index, count);
            }
            catch (Exception ex)
            { ///读取失败。
                throw ex;
            }

        }
        public async Task<NetMessage> ReadNetMessageAsync() => await Task<NetMessage>.Run(new Func<NetMessage>(this.ReadNetMessage));

        public NetMessage ReadNetMessage()
        {
            foreach (var item in NetMessageStreamWriter.signstart)
            {
                var b = ReadByte();
                if (b != item)
                {
                    throw new Exception("当前数据流中的内容不是有效的NetMessage，无效的起始字节。");
                }
            }
            NetMessage msg = new NetMessage();
            var headlength = ReadInt32();
            var bodylength = ReadInt64();

            var headbytes = ReadBytes(headlength);
            var json = (msg.Encoding ?? System.Text.Encoding.UTF8).GetString(headbytes);
            msg.Head = JsonConvert.DeserializeObject(json);
            var bodypos = 12 + headlength;
            if (bodylength == 0)
            {
                msg.Body = null;
            }
            else
            {
                msg.Body = new SectionStream(this.BaseStream, bodypos, bodylength);
            }


            return msg;
            //foreach (var item in NetMessageStreamWriter.signend)
            //{
            //    if (ReadByte() != item)
            //    {
            //        throw new Exception("当前数据流中的内容不是有效的NetMessage，无效的结束字节。");
            //    }
            //}

        }
    }
}
